import { reactive } from "vue";
import { ByteView, U8 } from "./codec";
import { Message } from "./message";
import { addr, heat, main, pub, weight } from "./proto";
import { onHeatStatus } from "./heat_def";
import { onWeightStatus } from "./weight_def";
import { onMainState } from "./main_def";
import { heat_action_msg, main_action_msg } from "./ec";

interface LogInfo {
    master: string[],
    heat: string[],
    weight: string[],
    action: string[],
}

export const logInfo = reactive<LogInfo>({
    master: [],
    heat: [],
    weight: [],
    action: [],
});


function onLog(msg: Message) {
    const bw = new ByteView();
    msg.parseResult(bw);
    const log_msg = bw.toString();
    console.log("日志", log_msg);
}

function onMainCookingAction(msg: Message) {
    const action = new U8();
    const ec = new U8();
    msg.parseResult(action, ec);
    const action_msg = main_action_msg(action.value, ec.value);
    logInfo.action.push(action_msg);
}

function onHeatCookingAction(msg: Message) {
    const action = new U8();
    const ec = new U8();
    msg.parseResult(action, ec);
    const action_msg = heat_action_msg(action.value, ec.value);
    logInfo.action.push(action_msg);
}

function handleMain(msg: Message) {
    const cmd = msg.query_result_cmd();

    switch (cmd) {
        case pub.LOG: onLog(msg); break;
        case main.STATUS: onMainState(msg); break;
        case main.COOKING_ACTION: onMainCookingAction(msg); break;
    }
}

function handleHeat(msg: Message) {
    const cmd = msg.query_result_cmd();

    switch (cmd) {
        case pub.LOG: onLog(msg); break;
        case heat.STATUS: onHeatStatus(msg); break;
        case heat.COOKING_ACTION: onHeatCookingAction(msg); break;
    }
}

function handleWeight(msg: Message) {
    const cmd = msg.query_result_cmd();

    switch (cmd) {

        case pub.LOG: onLog(msg); break;
        case weight.STATUS: onWeightStatus(msg); break;
    }
}

export function onNotify(msg: Message) {
    const src = msg.src();

    switch (src) {

        case addr.MAIN: handleMain(msg); break;

        case addr.HEAT: handleHeat(msg); break

        case addr.WEIGHT: handleWeight(msg); break

    }
}

